package mypazar.agent;

import jason.environment.grid.Location;
import mypazar.jenamodel.InitialPazarBeliefBase;
import mypazar.jenamodel.PazarVocabulary;
import mypazar.pazar.PazarModel;

import org.apache.log4j.Logger;

import tr.edu.ege.seagent.core.Seagent;
import tr.edu.ege.seagent.core.platform.SeagentPlatform;
import tr.edu.ege.seagent.planner.htn.Action;

import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;

public class SalesmanAgent extends Action {

	private static Logger logger = Logger.getLogger(SalesmanAgent.class);

	private Seagent seagentAgent;

	private Location locAgent;

	@SuppressWarnings("unused")
	private String agName;

	private Model beliefBase;

	public SalesmanAgent(String agentName, SeagentPlatform seagentPlatform,
			PazarModel model, Location location) {
		this.seagentAgent = createAgent(agentName, seagentPlatform, model);
		this.locAgent = location;
		this.agName = agentName;
		beliefBase = new InitialPazarBeliefBase().createRDFModel(agentName);
		seagentAgent.addHeapItem(PersonAgent.BELIEF_BASE_ITEM_NAME, beliefBase);
		// add initial location to belief-base here ..............
		setSalesmanAgentLoc(locAgent, PazarVocabulary.NS_URI + agentName,
				beliefBase);
		logger.info(agentName + " has located on (" + locAgent.x + ","
				+ locAgent.y + ")");
	}

	private void setSalesmanAgentLoc(Location locationAgent,
			String salesmanURI, Model beliefBase) {

		Resource resPerson = beliefBase.getResource(salesmanURI);
		Resource resPersonLoc = getAgentPositionNode(resPerson);

		resPersonLoc
				.removeAll(
						ResourceFactory
								.createProperty(PazarVocabulary.POS_X_URI))
				.removeAll(
						ResourceFactory
								.createProperty(PazarVocabulary.POS_Y_URI))
				.addProperty(beliefBase.getProperty(PazarVocabulary.POS_X_URI),
						Integer.toString(locationAgent.x),
						XSDDatatype.XSDinteger)
				.addProperty(beliefBase.getProperty(PazarVocabulary.POS_Y_URI),
						Integer.toString(locationAgent.y),
						XSDDatatype.XSDinteger);
	}

	private Resource getAgentPositionNode(Resource resPerson) {
		StmtIterator iterPerson = resPerson.listProperties(ResourceFactory
				.createProperty(PazarVocabulary.POSITION_URI));

		Statement stmtPersonLoc = iterPerson.next();

		Resource resPersonLoc = stmtPersonLoc.getObject().asResource();
		return resPersonLoc;
	}

	private Seagent createAgent(String agentName, SeagentPlatform platform,
			PazarModel model) {
		// create an agent in the platform...
		Seagent agent = platform.createAgent(agentName,
				PersonAgent.ORG_KNOWLEDGE_DIR, platform.getACC());
		agent.addHeapItem(PersonAgent.MODEL_ITEM_NAME, model);

		return agent;
	}

}
